/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.spider.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.spider.common.SpiderMonitorTask;
import com.thinkgem.jeesite.modules.spider.entity.SpiderLog;
import com.thinkgem.jeesite.modules.spider.pipeline.StackoverflowUserPipeline;
import com.thinkgem.jeesite.modules.spider.processor.StackoverflowUserProcessor;
import com.thinkgem.jeesite.modules.spider.service.SpiderLogService;
import com.thinkgem.jeesite.modules.spider.utils.RedisHelper;
import com.virjar.dungproxy.client.webmagic.DungProxyDownloader;

import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.scheduler.RedisScheduler;

/**
 * stackoverflow用户Controller
 * 
 * @author hongye
 * @version 2017-04-11
 */
@Controller
@RequestMapping(value = "${adminPath}/spider/stackoverflowUser")
public class StackoverflowUserController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Spider spider;
	private SpiderMonitorTask task;
	@Autowired
	private StackoverflowUserPipeline userPipeline;
	@Autowired
	private SpiderLogService logService;

	public void init() {
		if (spider == null) {
			spider = Spider.create(new StackoverflowUserProcessor()).setDownloader(new DungProxyDownloader())
					.addPipeline(userPipeline).setScheduler(new RedisScheduler(new RedisHelper().getJedisPool()));
			Request request = new Request("http://stackoverflow.com/users");
			spider.addRequest(request);
		} else {
			logger.debug("Thread Number=====>" + spider.getThreadAlive());
		}

		if (task == null) {
			task = new SpiderMonitorTask(spider, logService);
			task.start();
		}
	}

	@RequestMapping("/startJob")
	public String startJob(Model model) {
		init();
		if (spider != null && spider.getThreadAlive() == 0) {
			try {
				spider.thread(500).start();
			} catch (Exception e) {
				logService.save(new SpiderLog(this.getClass().toString(), "ERROR", e.getLocalizedMessage()));
				logger.error("spider running error==>{}", e.getLocalizedMessage());
				e.printStackTrace();
			}
		}
		logger.debug("start==" + this.getClass().toString() + sdf.format(new Date()));
		model.addAttribute("AliveThreadNum", spider.getThreadAlive());
		model.addAttribute("SpiderName", "XX Links");

		return "/spiders/common/SpiderStatus";
	}

	@RequestMapping("/restartJob")
	public String restartJob(Model model) {
		while (spider != null) {
			try {
				Thread.sleep(10000);
				if (spider.getThreadAlive() == 0) {
					spider.stop();
					Thread.sleep(1000);
					spider.start();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

		model.addAttribute("AliveThreadNum", spider.getThreadAlive());
		model.addAttribute("SpiderName", "XX Links");
		return "/spiders/common/SpiderStatus";
	}

	@RequestMapping("/stopJob")
	public String stopJob(Model model) {
		if (spider != null) {
			spider.stop();
			spider = null;
			logger.debug("stop==" + this.getClass().toString() + sdf.format(new Date()));

			model.addAttribute("AliveThreadNum", spider.getThreadAlive());
			model.addAttribute("SpiderName", "XX Links");
		}

		return "spiders/common/SpiderStatus";
	}

	public boolean isSpiderRunning() {
		if (spider == null) {
			return false;
		}
		return this.spider.getThreadAlive() > 0;
	}

	public int aliveThreadNum() {
		if (spider == null) {
			return 0;
		}
		return spider.getThreadAlive();
	}

	public Spider getSpider() {
		return spider;
	}

	public void setSpider(Spider spider) {
		this.spider = spider;
	}

}